package com.linkage.educloud.ah.view.activity.topic;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.linkage.educloud.ah.Constants;
import com.linkage.educloud.ah.R;
import com.linkage.educloud.ah.adapter.topic.TopicChooseImgAdapter;
import com.linkage.educloud.ah.bean.AccountData;
import com.linkage.educloud.ah.config.AccountConfig;
import com.linkage.educloud.ah.mvp.contract.topic.ITopicWriterContract;
import com.linkage.educloud.ah.mvp.presenter.topic.TopicWriterPresenter;
import com.linkage.educloud.ah.view.BasicTitleActivity;
import com.linkage.educloud.ah.widget.ChoosePicDialog;
import com.linkage.educloud.ah.widget.NoScrollGridView;
import com.linkage.educloud.ah.widget.PanelView;
import com.zzhou.common.library.util.ToastShow;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Mr'Tang on 2018/12/6.
 */

public class TopicWriterActivity extends BasicTitleActivity implements ITopicWriterContract.IView {

    //使用BindView后 如果需要传递这个view会报空指针,所以这里我采用传统的findviewbyid
    EditText ac_topic_writer_content;

    @BindView(R.id.ac_topic_writer_title)
    EditText ac_topic_writer_title;
    @BindView(R.id.ac_topic_writer_imggrid)
    NoScrollGridView ac_topic_writer_imggrid;
    @BindView(R.id.ac_topic_writer_face)
    ImageView ac_topic_writer_face;
    @BindView(R.id.ac_topic_writer_pic)
    ImageView ac_topic_writer_pic;
    @BindView(R.id.ac_topic_writer_textnum)
    TextView ac_topic_writer_textnum;
    @BindView(R.id.ac_topic_writer_panel)
    PanelView ac_topic_writer_panel;

    AccountData accountData;
    int is_visibility = 1;//表情是否展示中
    List<Uri> img_list = new ArrayList<>();
    TopicChooseImgAdapter adapter;
    String picurls;

    ITopicWriterContract.IPresenter iPresenter;

    private static final String KEY_id = "topic_id";

    public static void launch(Context context, String topic_id) {
        Intent intent = new Intent(context, TopicWriterActivity.class);
        intent.putExtra(KEY_id, topic_id);
        context.startActivity(intent);
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_topic_writer;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        accountData = AccountConfig.getLoginAccount();
        iPresenter = new TopicWriterPresenter(this, this);
        ac_topic_writer_content = findViewById(R.id.ac_topic_writer_content);
        initFace();
        addTextChangedListener();
        send();
    }

    private void send() {
        if (ac_topic_writer_title.getText().toString().trim().isEmpty()) {
            ToastShow.show(this, "标题不能为空！");
            return;
        }
        if (ac_topic_writer_content.getText().toString().trim().isEmpty()) {
            ToastShow.show(this, "内容不能为空！");
            return;
        }
        iPresenter.pushCard(getIntent().getStringExtra(KEY_id), picurls, ac_topic_writer_title.getText().toString().trim(), ac_topic_writer_content.getText().toString().trim());
    }

    private void addTextChangedListener() {
        ac_topic_writer_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                int number = s.length();
                ac_topic_writer_textnum.setText(number + "/500");
                if (number == 500) {
                    ac_topic_writer_textnum.setTextColor(getResources().getColor(R.color.tab_color_true));
                } else {
                    ac_topic_writer_textnum.setTextColor(getResources().getColor(R.color.black));
                }
            }
        });
    }


    //初始化表情相关
    private void initFace() {
        setTitle("发帖子");
        ac_topic_writer_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (adapter.getCount() == 6) {
                    ToastShow.show(TopicWriterActivity.this, "最多只能添加6张图片，点击图片可以编辑当前已选择的图片!");
                }
                final ChoosePicDialog dialog = new ChoosePicDialog(TopicWriterActivity.this);
                dialog.setShotListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        startActivityForResult(ChoosePicDialog.gotoShot("xiaoma.jpg"), Constants.PIC.PIC_Shot);
                    }
                });
                dialog.setAlbumListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        startActivityForResult(ChoosePicDialog.gotoAlbum(), Constants.PIC.PIC_ALBUM);
                    }
                });
                dialog.show();
            }
        });

        adapter = new TopicChooseImgAdapter(this, img_list);
        ac_topic_writer_imggrid.setAdapter(adapter);

        ac_topic_writer_panel.installView(2, 2, ac_topic_writer_content);
        ac_topic_writer_face.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (is_visibility == 1) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    //延时0.3秒 以解决表情栏展示比隐藏输入法快,界面被顶上去的bug（目前没想到其他好方法）
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ac_topic_writer_panel.setVisibility(View.VISIBLE);
                        }
                    }, 300);
                    is_visibility = 0;
                } else if (is_visibility == 0) {
                    ac_topic_writer_panel.setVisibility(View.GONE);
                    is_visibility = 1;
                }
            }
        });
    }

    //暴露给表情组件调用 用于点了输入框改变表情状态
    public void change() {
        ac_topic_writer_panel.setVisibility(View.GONE);
        is_visibility = 1;
    }

    //选择照片回调相关
    @Override
    public void onActivityResult(int requestCode, int resultCode,
                                 final Intent data) {
        switch (requestCode) {
            case Constants.PIC.PIC_ALBUM://相册选择回调
                if (data != null) {
                    Uri uri = data.getData();
                    img_list.add(uri);
                    adapter.notifyDataSetChanged();
                }
                break;
            case Constants.PIC.PIC_Shot://拍摄界面回调
                if (resultCode == RESULT_CANCELED) {
                    return;
                }
                File temp = new File(Environment.getExternalStorageDirectory()
                        + "/xiaoma.jpg");
                Uri uri = Uri.fromFile(temp);
                img_list.add(uri);
                adapter.notifyDataSetChanged();
                break;
        }
    }
}
